//
//  XYXEmoticonModel.swift
//  Emoticon
//
//  Created by 亚杏 on 2017/6/5.
//  Copyright © 2017年 oms. All rights reserved.
//

import UIKit
import YYModel

class XYXEmoticonModel: NSObject {

    ///表情类型 false - 图片表情、 true - emoji
    var type = false
    /// 表情字符串，发送给新浪的服务器（节约流量）
    var chs: String?
    /// 表情图片名称，用于本地图文混排
    var png: String?
    // emoji 的十六进制编码
    var code: String? {
        didSet {
            guard let code = code else {
                return
            }

            //字符扫描
            let scanner = Scanner(string: code)

            //从code中扫描出 十六进制的数值,result是一个十进制数值
            var result: UInt32 = 0
            scanner.scanHexInt32(&result)
            emoji = String(Character(UnicodeScalar(result)!))
        }
    }
    var times: Int = 0
    
    //emoji的字符串
    var emoji: String?

    // 表情模型所在的目录
    var directory: String?
    // 图片表情对应的图像
    var image: UIImage? {
        if type {
            return nil
        }

        guard let directory = directory,
              let png = png,
              let path = Bundle.main.path(forResource: "HMEmoticon.bundle", ofType: nil),
              let bundle = Bundle(path: path),
              let image = UIImage(named: "\(directory)/\(png)", in: bundle, compatibleWith: nil)
        else {
            return nil
        }
        return image
    }

    //将当前的图像转换生成图片的属性文本
    func imageText(font: UIFont) -> NSAttributedString {

        //1.判断图像是否存在
        guard let image = image else {
            return NSAttributedString(string: "")
        }

        let attachment = XYXEmoticonAttachment()
        attachment.chs = chs
        attachment.image = image
        let height = font.lineHeight
        attachment.bounds = CGRect(x: 0, y: -4, width: height, height: height)

        //3.返回图片属性文本
        let attrStr = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
        //设置图像文字的属性
        attrStr.addAttributes([NSFontAttributeName: font], range: NSRange(location: 0, length: 1))

       return attrStr

    }

    override var description: String {
        return yy_modelDescription()
    }
}
